package com.tuanproject.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.tuanproject.model.Events;

/**
 * 
 * @author TuanLe
 *
 */
@Repository
public class EventsDAO extends GenericDAO<Events> {

	/**
	 * get all object in database
	 * 
	 * @return List
	 * @throws SQLException
	 */
	public List<Events> getAllObject() throws SQLException {

		String sql = "select * from events";
		List<Events> list = new ArrayList<Events>();
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		list = jdbcTemplate.query(sql, new RowMapper<Events>() {
			@Override
			public Events mapRow(ResultSet rs, int rowNum) throws SQLException {
				return getDataFromResultSet(rs, rowNum);
			}
		});
		return list;
	}
	/**
	 * get list userProfile by userName
	 * 
	 * @param userName
	 * @return List<Events>
	 */
	public List<Events> getEventsByTime(String fromDate, String toDate) {
		
		String sql = "select * from events where 1 ";
		List<Object> properties = new ArrayList<Object>();
		if (fromDate != "") {
			sql += "and events.time >= ? ";
			properties.add(fromDate);
		}
		
		if (toDate != "") {
			sql += "and events.time <= ? ";
			properties.add(toDate);
		}
		
		List<Events> eventsList = new ArrayList<Events>();
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		eventsList = jdbcTemplate.query(sql, properties.toArray(),
				new RowMapper<Events>() {
					@Override
					public Events mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Events events = getDataFromResultSet(rs, rowNum);
						return events;
					}
				});
		return eventsList;
	}

	/**
	 * get Object by id
	 * 
	 * @param Id
	 * @return
	 * @throws SQLException
	 */
	public Events getById(int id) throws SQLException {

		String sql = "select * from events where id = " + id;

		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		Events object = jdbcTemplate.queryForObject(sql, new Object[] { id },
				new RowMapper<Events>() {
					@Override
					public Events mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						return getDataFromResultSet(rs, rowNum);
					}
				});
		return object;
	}
	
	@Override
	public Events getDataFromResultSet(ResultSet rs, int rowNum)
			throws SQLException {
		Events events = new Events();
		events.setTime(rs.getString("time"));
		events.setSource(rs.getString("source"));
		events.setRequestRaw(rs.getString("request_raw"));
		events.setPattern(rs.getString("pattern"));
		return events;
	}
}
